package main.java.br.com.projeto.domain.dao;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.persistence.PersistenceException;

import main.java.br.com.projeto.domain.entity.Compra;

public class DaoCompra extends Dao<Compra> {

	/**
	 * 
	 */
	private static final long serialVersionUID = -3921859088784293258L;

	public DaoCompra() {
		super(Compra.class);
	}
	
	public Compra findByPK(String numeroNota, String numeroSerie, Long fornecedorId) {
		String hql = "select Compra from Compra compra "
				+ "where compra.notaPK.numeroNota = :numeroNota " 
				+ "and compra.notaPK.numeroSerie = :numeroSerie "
				+ "and compra.fornecedor.id = :fornecedorId";

		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("numeroNota", numeroNota);
		parameters.put("numeroSerie", numeroSerie);
		parameters.put("fornecedorId", fornecedorId);

		List<Compra> listCompra = this.findOneResult(hql, parameters);
		
		if ( listCompra.size() > 0 )
		{
			return listCompra.get(0);
		}
		return null;
	}
	
	public Compra insert(Compra entity) {
		try {
			this.beginTransaction();		
			getManager().persist(entity);
			this.commit();
			this.closeTransaction();
			return entity;
		} catch (PersistenceException e) {
			return this.update(entity);
		} catch (Exception e2) {
			this.rollback();
			e2.printStackTrace();
			return null;
		}
	}
	
	public List<Compra> listByFilter(String numeroNota, String numeroSerie, String fornecedor, Date dataEmissao) {
		String hql = "select compra from Compra compra "
				+ "where (lower(compra.notaPK.numeroNota) like '%' || lower ( cast(:numeroNota as string) ) || '%' or :numeroNota = null) "
				+ "and (lower(compra.notaPK.numeroSerie) like '%' || lower ( cast(:numeroSerie as string) ) || '%' or :numeroSerie = null) "
				+ "and (compra.fornecedor.nome like '%' || cast(:fornecedor  as string) || '%' or :fornecedor = null) "
				+ "and (compra.emissao = :dataEmissao or cast(:dataEmissao as date) = null)";

		Map<String, Object> parameters = new HashMap<String, Object>();
		parameters.put("numeroNota", numeroNota);
		parameters.put("numeroSerie", numeroSerie);
		parameters.put("fornecedor", fornecedor);
		parameters.put("dataEmissao", dataEmissao);

		return this.findOneResult(hql, parameters);
	}	
}
